<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Promise 灯光循环变化</title>
    <style>
        body {
            display: flex;
            height: 100vh;
            margin: 0;
            justify-content: center;
        }

        .container {
            text-align: center;
        }

        #light {
            width: 200px;
            height: 200px;
            border-radius: 50%;
            background-color: black;
        }

        .status {
            font-size: 16px;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>灯光循环变化</h2>
    <div id="light"></div>
    <p class="status">准备......</p>
</div>

<script>
    const light = document.getElementById('light');
    const status = document.querySelector('.status');

    let intervalId = null;//存储定时器唯一标识(存储setTimeout的返回值)

    updateColor('black', '准备......');

    function updateColor(color, info) {
        light.style.backgroundColor = color;
        status.textContent = info;
    }

    function delayPromise(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function startChange() {
        updateColor('red', '红灯(3s)');

        delayPromise(3000)
            .then(() => {
                updateColor('yellow', '黄灯(2s)');
                return delayPromise(2000);
            })
            .then(() => {
                updateColor('green', '绿灯(1s)');
                return delayPromise(1000);
            })
            .then(() => {
                intervalId = setTimeout(startChange, 100);//循环
            });
    }

    window.addEventListener('load', startChange);//页面加载完就启动
</script>

</body>
</html>